<template>
	<div class="system-role-dialog-container">
		<el-dialog :title="state.dialog.title" center class="borderRadius10" v-model="state.dialog.isShowDialog" width="490">
            <el-form ref="roleDialogFormRef" :rules="rules" :model="state.ruleForm" label-width="120px">
                <el-form-item label="分类类型：" prop="platformType">
                    <el-select class="width260" v-model="state.ruleForm.platformType" placeholder="请选择分类类型" @change="changeCategoryType">
                        <el-option :key=1 label="商城商品分类" :value=0 />
                        <el-option :key=2 label="门店商品分类" :value=1 />
                    </el-select>
                </el-form-item>
                <el-form-item label="上级分类：" prop="superCategoryPath">
                    <el-cascader class="width260" v-model="state.ruleForm.superCategoryPath"
                        placeholder="请选择上级分类" :options="state.productCategoryList"
                        :props="{ label: 'text', value: 'id', children: 'children' }" />
                </el-form-item>
                <el-form-item label="分类名称：" prop="categoryName">
                    <el-input class="width260" v-model="state.ruleForm.categoryName" placeholder="请输入分类名称" />
                </el-form-item>
                <el-form-item label="分类图标(1:1)：">
                    <section @click="addImg('categoryUrl', 0)">
                        <el-image v-if="state.ruleForm.categoryUrl != '' && state.ruleForm.categoryUrl != null" class="mr20"
                            style="width:64px; height: 64px;border-radius: 5px;" :src="state.ruleForm.categoryUrl"
                            fit="cover" />
                        <section v-else class="selector-img">
                            <el-icon size="30" color="#999">
                                <Plus />
                            </el-icon>
                        </section>
                    </section>
                </el-form-item>
                <el-form-item label="分类大图(4:1)：">
                    <section @click="addImg('categoryBigUrl', 0)">
                        <el-image v-if="state.ruleForm.categoryBigUrl != '' && state.ruleForm.categoryBigUrl != null" class="mr20"
                            style="width:256px; height: 64px;border-radius: 5px;" :src="state.ruleForm.categoryBigUrl"
                            fit="cover" />
                        <section v-else class="selector-img" style="width: 256px;height: 64px;">
                            <el-icon size="30" color="#999">
                                <Plus />
                            </el-icon>
                        </section>
                    </section>
                </el-form-item>
                <el-form-item label="排序：">
                    <el-input-number class="width260" v-model="state.ruleForm.sortNumber" :precision="0" :step="1"
                        :min="0" :max="10000" />
                </el-form-item>
            </el-form>
            <el-row justify="center" class="mt20">
                <el-button @click="closeDialog">取消</el-button>
                <el-button type="primary" @click="onSubmitForm(roleDialogFormRef)">确定</el-button>
            </el-row>
		</el-dialog>
        <AddInformation ref="addInformationRef" @selectFun="selectFun" />
	</div>
</template>

<script setup lang="ts">

import { reactive, ref, defineAsyncComponent } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { productCategoryList, productCategoryUpsert } from "/@/api/commodity";
const AddInformation = defineAsyncComponent(() => import('/@/components/information/AddInformation.vue'))
// 定义变量内容
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
const roleDialogFormRef = ref<FormInstance>()
const addInformationRef = ref();
const state = reactive({
    loading: false,
    addFileType: '',
    dialog: {
        isShowDialog: false,
        type: 'add',
        title: '',
        submitTxt: '',
    },
    ruleForm: {
        platformType: 1,
        categoryId: null,
        categoryName: '', // 模板名称
        superCategoryPath: [] as Array<number>,
        categoryUrl: '',
        categoryBigUrl: '',
        sortNumber: 1,
    },
    // 商品分类list
    productCategoryList: [] as Array<any>,
})

const rules = reactive<FormRules<any>>({
    platformType: [{ required: true, message: '请选择商品分类类型', trigger: 'change' }],
    superCategoryPath: [{ required: true, message: '请选择商品上级分类', trigger: 'change' }],
    categoryName: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
})


// 分类类型切换 清空选择的上级分类项
const changeCategoryType = () => {
    state.ruleForm.superCategoryPath = [];
}

// 打开弹窗
const openDialog = (type: string, platformType: number, row?: any) => {
    state.dialog.type = type;
    console.log(row)
    if (type === 'edit') {
        state.dialog.title = '商品分类编辑';
        state.dialog.submitTxt = '修 改';
        state.ruleForm = {
            platformType: platformType,
            categoryId: row.categoryId,
            categoryName: row.categoryName, // 模板名称
            superCategoryPath: row.superCategoryPath,
            categoryUrl: row.categoryUrl,
            categoryBigUrl: row.categoryBigUrl,
            sortNumber: row.sortNumber,
        };
    } else {
        state.dialog.title = '商品分类新增';
        state.dialog.submitTxt = '新 增';
        state.ruleForm = {
            platformType: platformType,
            categoryId: null,
            categoryName: '', // 模板名称
            superCategoryPath: [] as Array<number>,
            categoryUrl:'',
            categoryBigUrl: '',
            sortNumber: 0,
        };
    }
    getCategoryList();
    state.dialog.isShowDialog = true;
};


// 获取商品分类
const getCategoryList = async () => {
    // 创建一个新的对象  
    let obj = { text: '无上级', id: 0, };
    const { results } = await productCategoryList({ platformType:  state.ruleForm.platformType });
    state.productCategoryList = results
    state.productCategoryList.unshift(obj);
}

const closeDialog = () => {
    state.dialog.isShowDialog = false;
}

const onSubmitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate(async (valid: boolean) => {
        if (valid) {
            state.loading = true;
            let params = {
                platformType: state.ruleForm.platformType,
                categoryId: state.ruleForm.categoryId,
                categoryName: state.ruleForm.categoryName, // 模板名称
                superCategoryPath: state.ruleForm.superCategoryPath,
                categoryUrl: state.ruleForm.categoryUrl,
                categoryBigUrl: state.ruleForm.categoryBigUrl,
                sortNumber: state.ruleForm.sortNumber,
            }
            const { data } = await productCategoryUpsert(params);
            if (state.dialog.type == 'edit') {
                ElMessage.success('修改成功');
            } else {
                ElMessage.success('新增成功');
            }
            state.loading = false;
            closeDialog();
            emit('refresh');
        } else {
            return false;
        }
    });
};

// 图片选中
const addImg = (type: string, isArr: Number) => {
    state.addFileType = type;
    addInformationRef.value.openDialog(isArr)
}

// 图片选中回调
const selectFun = (fileList: any) => {
    if (state.addFileType == 'categoryUrl') {
        state.ruleForm.categoryUrl = fileList[0]
    } else if (state.addFileType == 'categoryBigUrl') {
        state.ruleForm.categoryBigUrl = fileList[0]
    }
}

// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style lang='scss' scoped>
.selector-img {
    width: 64px;
    height: 64px;
    border: 1px solid #ededed;
    border-radius: 5px;
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;

    &:hover {
        background-color: #f5f5f5;
        border: 1px solid #e4e3e3;
    }
}
</style>